// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package metrics

import (
	"reflect"
	"testing"
	"unsafe"

	"github.com/prometheus/client_golang/prometheus"
)

func TestTimeXCollector_MetricUniqueness_RegisterError(t *testing.T) {
	tests := []struct {
		name      string
		setup     func(*TimeXCollector)
		expectErr bool
	}{
		{
			name:      "正常指标集合",
			setup:     func(c *TimeXCollector) {},
			expectErr: false,
		},
		{
			name: "注入重复名称不同类型指标",
			setup: func(c *TimeXCollector) {
				v := reflect.ValueOf(c).Elem()
				f := v.FieldByName("metrics")
				ptr := unsafe.Pointer(f.UnsafeAddr())
				m := *(*map[string]*MetricDesc)(ptr)

				m["duplicate_offset"] = &MetricDesc{
					Desc: prometheus.NewDesc(
						prometheus.BuildFQName(namespace, "timex", "offset_seconds"), // 同名指标名
						"Fake duplicate offset with different type",
						nil,
						nil,
					),
					Type: prometheus.CounterValue, // 与原来的 GaugeValue 不同
				}
			},
			expectErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := NewTimeXCollector()
			tt.setup(c)

			reg := prometheus.NewRegistry()
			err := reg.Register(c)
			if (err != nil) != tt.expectErr {
				t.Errorf("注册重复指标预期是否出错不符: 期望错误=%v 实际错误=%v", tt.expectErr, err)
			}
			if err != nil && !tt.expectErr {
				t.Logf("register error detail: %v", err)
			}
		})
	}
}
